<?php
/**
 * Created by mq.
 * User: mq
 * Date: 17-9-25
 * Time: 下午9:16
 */

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Request;
use think\Session;

class Login extends Controller
{
    function index()
    {
        if (is_login()) $this->redirect(url('/admin'));

        if (Request::instance()->isPost()) {
            $name = trim($_POST['username']);
            $password = trim($_POST['password']);
            $url = url('/admin/login');

            //表单验证
            $formVerify = $this->validate(
                $_POST,
                ['username' => 'require', 'password' => 'require', 'verify' => 'require'],
                ['username' => '用户名不能为空', 'password' => '密码不能为空', 'verify' => '验证码不能为空']
            );
            if ($formVerify !== true) $this->error($formVerify, $url);

            //验证码验证
            $captcha = new \tool\captcha\Captcha(config('captcha'));
            $verify = $captcha->check(trim($_POST['verify']));
            if (!$verify) $this->error('验证码错误！', $url);

            //用户密码验证
            $userInfo = db('admin')->where('username', $name)->find();
            if ($userInfo) {
                $postPassword = md5(md5($password) . md5(config('web_key')));

                if ($postPassword == $userInfo['password']) {
                    $loginInfo = [
                        'name' => $userInfo['username'],
                        'id' => $userInfo['id'],
                        'auth' => $userInfo['auth'] ? explode(',', $userInfo['auth']):[],
                        'super' => $userInfo['super']
                    ];
                    Session::set('user', $loginInfo);
                    Db::table('admin')->where(['id' => $userInfo['id']])->update(['last_login_time'=>time()]);
                    $this->redirect(url('/admin'));
                } else {
                    $this->error('密码错误！');
                }
            } else {
                $this->error('不存在的用户！');
            }
        }

        return $this->fetch();
    }

    function logout()
    {
        Session::delete('user');
        $this->success('成功退出！', url('/admin/login'), '', 0);
    }
}